package com.zenithmind.common.config;

import com.zenithmind.common.interceptor.AuthInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
 * 认证拦截器自动配置
 * 用于各个微服务自动配置认证拦截器
 */
@Slf4j
@Configuration
@ConditionalOnProperty(prefix = "zenithmind.auth", name = "enabled", havingValue = "true", matchIfMissing = true)
public class AuthInterceptorConfig implements WebMvcConfigurer {

    /**
     * 认证配置属性
     */
    @ConfigurationProperties(prefix = "zenithmind.auth")
    public static class AuthProperties {
        /**
         * 是否启用认证
         */
        private boolean enabled = true;

        /**
         * 是否启用严格模式（必须有用户信息）
         */
        private boolean strictMode = true;

        /**
         * 跳过认证的路径列表
         */
        private List<String> skipPaths;

        public boolean isEnabled() {
            return enabled;
        }

        public void setEnabled(boolean enabled) {
            this.enabled = enabled;
        }

        public boolean isStrictMode() {
            return strictMode;
        }

        public void setStrictMode(boolean strictMode) {
            this.strictMode = strictMode;
        }

        public List<String> getSkipPaths() {
            return skipPaths;
        }

        public void setSkipPaths(List<String> skipPaths) {
            this.skipPaths = skipPaths;
        }
    }

    @Bean
    @ConfigurationProperties(prefix = "zenithmind.auth")
    public AuthProperties authProperties() {
        return new AuthProperties();
    }

    @Bean
    public AuthInterceptor authInterceptor(AuthProperties authProperties) {
        log.info("创建认证拦截器，严格模式: {}, 跳过路径: {}", 
                authProperties.isStrictMode(), authProperties.getSkipPaths());
        return new AuthInterceptor(authProperties.getSkipPaths(), authProperties.isStrictMode());
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        AuthProperties authProperties = authProperties();
        if (authProperties.isEnabled()) {
            registry.addInterceptor(authInterceptor(authProperties))
                    .addPathPatterns("/**");
            log.info("认证拦截器已注册");
        } else {
            log.info("认证拦截器已禁用");
        }
    }
}
